package com.xincheng.shuimalong.activity.sell;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.xincheng.library.util.CommonUtil;
import com.xincheng.library.util.PrefUtil;
import com.xincheng.library.util.UIUtil;
import com.xincheng.library.widget.StateButton;
import com.xincheng.library.widget.alertview.AlertView;
import com.xincheng.library.widget.alertview.OnAlertDismissListener;
import com.xincheng.library.widget.alertview.OnAlertItemClickListener;
import com.xincheng.library.xlog.XLog;
import com.xincheng.library.xswipemenurecyclerview.holder.RecyclerHolder;
import com.xincheng.library.xswipemenurecyclerview.listener.OnItemClickListener;
import com.xincheng.shuimalong.R;
import com.xincheng.shuimalong.activity.BaseActivity;
import com.xincheng.shuimalong.activity.PayActivity;
import com.xincheng.shuimalong.activity.SucceedActivity;
import com.xincheng.shuimalong.activity.address.AddressAddActivity;
import com.xincheng.shuimalong.activity.address.AddressManagementActivity;
import com.xincheng.shuimalong.activity.bank.BankCardAddActivity;
import com.xincheng.shuimalong.activity.mydetail.setting.BindPhoneActivity;
import com.xincheng.shuimalong.api.AppUrl;
import com.xincheng.shuimalong.api.BaseObserver;
import com.xincheng.shuimalong.api.GetParam;
import com.xincheng.shuimalong.api.PostParam;
import com.xincheng.shuimalong.api.RetroSubscrube;
import com.xincheng.shuimalong.common.IntentKey;
import com.xincheng.shuimalong.common.PrefKey;
import com.xincheng.shuimalong.common.RequestCodeKey;
import com.xincheng.shuimalong.entity.address.Address;
import com.xincheng.shuimalong.entity.bank.BankCard;
import com.xincheng.shuimalong.entity.config.CommonConfig;
import com.xincheng.shuimalong.entity.config.RegionData;
import com.xincheng.shuimalong.entity.user.UserHome;
import com.xincheng.shuimalong.manager.OrderExitManager;
import com.xincheng.shuimalong.util.ConfigUtil;
import com.xincheng.shuimalong.util.GsonUtil;
import com.xincheng.shuimalong.util.MyUtil;
import com.xincheng.shuimalong.util.ShowActivity;
import com.xincheng.shuimalong.view.PasswordView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by xiaote on 2017/6/29.
 */

public class PayOrderActivity extends BaseActivity {
    @BindView(R.id.payorder_address_username_tv)
    TextView mUsernameTv;
    @BindView(R.id.payorder_address_mobile_tv)
    TextView mMobileTv;
    @BindView(R.id.payorder_address_isdefault_tv)
    TextView mIsDefaultTv;
    @BindView(R.id.payorder_address_tv)
    TextView mAddressTv;
    @BindView(R.id.payorder_address_add_tv)
    TextView mAddressAddTv;
    @BindView(R.id.payorder_plateno_tv)
    TextView mPlateNoTv;
    @BindView(R.id.payorder_area_tv)
    TextView mAreaTv;
    @BindView(R.id.payorder_company_tv)
    TextView mCompanyTv;
    @BindView(R.id.payorder_paystyle_rg)
    RadioGroup mPayStyleRg;
    @BindView(R.id.payorder_totalmoney_tv)
    TextView mTotalMoneyTv;
    //    @BindView(R.id.payorder_paystyle_default_layout)
//    MRecyclerView mPayStyleDefaultLayout;
    @BindView(R.id.rv_walter_pay)
    RelativeLayout rv_walter_pay;
    @BindView(R.id.tv_transfer_id)
    TextView tvTransferId;
    @BindView(R.id.payorder_submit_btn)
    StateButton mSubmitBtn;
    List<BankCard.Data> dataList;
    @BindView(R.id.tv_wallet_money)
    TextView tvMyWalter;
    @BindView(R.id.imv_check_pay)
    ImageView imvCheckPay;
    private String mTotalMoney;
    private Address mAddress;
    private String mToken;
    private String bankNumber;
    private int mBidId;
    private boolean mAddressIsEmpty;
    private int mPayStatus = 3;
    private AlertView mMessageAlert;
    private AlertView mPassworAlert;
    private TextView[] mPwdTvList;
    private PasswordView mPasswordView;
    private String mUserId;
//    private PayBankCardAdapter mAdapter;

    @Override
    public int getLayoutResId() {
        return R.layout.activity_pay_order;
    }

    @Override
    public void initData() {
        initTitleBar(getString(R.string.pay_insurance_money));
        mPayStatus = 3;
        OrderExitManager.getInstance().addActivity(this);
        mAddressIsEmpty = true;
        showWidget(mAddressIsEmpty);
        mToken = PrefUtil.getString(this, PrefKey.TOKEN, "");
        Bundle extras = getIntent().getExtras();
        int provinceId = extras.getInt(IntentKey.PROVINCE);
        int cityId = extras.getInt(IntentKey.CITY);
        int companyId = extras.getInt(IntentKey.INSURANCE_COMPANY);
        String plateNo = extras.getString(IntentKey.PLATE_NO);
        mTotalMoney = extras.getString(IntentKey.TOTAL_MONEY);
        mBidId = extras.getInt(IntentKey.BID_ID);
        mPlateNoTv.setText(plateNo);
        if (provinceId != 0 && cityId != 0) {
            RegionData province = ConfigUtil.getProvince(this, provinceId);
            RegionData city = ConfigUtil.getCity(this, cityId);
            mAreaTv.setText(province.getName() + city.getName());
        }
        CommonConfig company = ConfigUtil.getCommonConfigById(this, PrefKey.COMPANY_LIST, companyId);
        if (company != null) {
            mCompanyTv.setText(company.getName());
        }
        mTotalMoneyTv.setText(getString(R.string.money_value, mTotalMoney));
        imvCheckPay.setSelected(true);
        tvTransferId.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//下划线
        mUserId = PrefUtil.getString(this, PrefKey.LOGIN_USER_ID, "");
        sellMessage();
        getAddress();
    }

//    private void setdefaultBank() {
//        if (dataList == null) {
//            dataList = new ArrayList<>();
//        } else {
//            dataList.clear();
//        }
//        mPayStatus = 3;
//        BankCard.Data bank = new BankCard.Data();
//        bank.setBank("钱包余额");
//        bank.setIsSelect(1);
//        dataList.add(0, bank);
//    }

    //卖单个人中心
    private void sellMessage() {
        RetroSubscrube.getInstance().getSubscrube(GetParam.getBillindex(PrefUtil.getString(getContext(),
                PrefKey.TOKEN, "")),
                new BaseObserver(this) {
                    @Override
                    protected void onHandleSuccess(Object data, String msg) {
                        if (data != null) {
                            UserHome management = GsonUtil.parseData(data, UserHome.class);
                            tvMyWalter.setText(getString(R.string.money_value, management.getAmount()));
                        }
                    }
                });
    }

    @OnClick({R.id.payorder_address_layout_tv, R.id.payorder_submit_btn, R.id.rv_walter_pay, R.id.tv_transfer_id})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_transfer_id:
                ShowActivity.showActivity(this, TransferActivity.class);
                break;
            case R.id.payorder_address_layout_tv:
                if (mAddressIsEmpty) {
                    ShowActivity.showActivityForResult(this, AddressAddActivity.class, RequestCodeKey.GO_ADD_ADDRESS);
                } else {
                    Bundle extras = new Bundle();
                    extras.putInt(IntentKey.FROM, 1);
                    if (mAddress != null) {
                        extras.putInt(IntentKey.ADDRESS_ID, mAddress.getAddressId());
                    }
                    ShowActivity.showActivityForResult(this, AddressManagementActivity.class, extras,
                            RequestCodeKey.GO_GET_ADDRESS);
                }
                break;
            case R.id.payorder_submit_btn:
                if (checkData()) {
                    payOrder();
                }
                break;
        }
    }

    private boolean checkData() {
        if (mAddress == null) {
            CommonUtil.showToast(this, "请添加收货地址");
            return false;
        }
        return true;
    }

    @Override
    public void addListener() {
        mPayStyleRg.setOnCheckedChangeListener(new MyOnCheckedChangedListener());
//        mPayStyleDefaultLayout.setOnItemClickListener(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RequestCodeKey.GO_GET_ADDRESS:
                case RequestCodeKey.GO_ADD_ADDRESS:
                    mAddress = data.getParcelableExtra(IntentKey.ADDRESS);
                    if (mAddress == null) {
                        mAddressIsEmpty = true;
                    } else {
                        mAddressIsEmpty = false;
                    }
                    showWidget(mAddressIsEmpty);
                    parseAddress();
                    break;
                case RequestCodeKey.GO_PAY:
                    Intent intent = new Intent();
                    intent.putExtra(IntentKey.PAY_SUCCESS, true);
                    setResult(RESULT_OK, intent);
                    finish();
                    break;
//                case RequestCodeKey.GO_ADD_BANKCARD:
//                    getBank();
//                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void getAddress() {
        RetroSubscrube.getInstance().getSubscrube(GetParam.getAddress(mToken),
                new BaseObserver(this) {
                    @Override
                    protected void onHandleSuccess(Object data, String msg) {
                        if (data != null) {
                            try {
                                List<Address> list = GsonUtil.parseData(data, new TypeToken<List<Address>>() {
                                }.getType());
                                if (CommonUtil.isEmpty(list)) {
                                    mAddressIsEmpty = true;
                                } else {
                                    mAddressIsEmpty = false;
                                    mAddress = MyUtil.getDefaultAddress(list);
                                    parseAddress();
                                }
                                showWidget(mAddressIsEmpty);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    private void payOrder() {
        XLog.e("mPayStatus=>开始加载..." + mPayStatus);
        switch (mPayStatus) {
//            case 1://在线支付
//                Bundle extras = new Bundle();
//                extras.putInt(IntentKey.BID_ID, mBidId);
//                extras.putInt(IntentKey.ADDRESS_ID, mAddress.getAddressId());
//                extras.putString(IntentKey.BANK_CARD_NO, bankNumber);
//                ShowActivity.showActivityForResult(this, PayActivity.class, extras, RequestCodeKey.GO_PAY);
//                break;
            case 2://线下支付
                RetroSubscrube.getInstance().postSubscrube(AppUrl.PAY_OFFLINE,
                        PostParam.payOrder(mToken, mBidId, mAddress.getAddressId()),
                        new BaseObserver(this, getString(R.string.loading_submit)) {
                            @Override
                            protected void onHandleSuccess(Object data, String msg) {
                                paySuccess();
                            }
                        });
                break;
            case 3://钱包支付
                boolean isSetPayPwd = PrefUtil.getBoolean(this, PrefKey.LOGIN_SET_PAYPWD, false);
                if (!isSetPayPwd) {
                    if (mMessageAlert == null) {
                        initMsgAlert();
                    }
                    mMessageAlert.show();
                } else {
                    if (mPassworAlert == null) {
                        initPasswordAlert();
                    }
                    mPassworAlert.show();
                }
                break;
        }
    }

    private void initPasswordAlert() {
        mPassworAlert = new AlertView(this, AlertView.Style.Alert);
        View view = LayoutInflater.from(this).inflate(R.layout.withdraw_desposit_dialog, null);
        mPwdTvList = new TextView[6];
        mPwdTvList[0] = UIUtil.findViewById(view, R.id.tv_pass1);
        mPwdTvList[1] = UIUtil.findViewById(view, R.id.tv_pass2);
        mPwdTvList[2] = UIUtil.findViewById(view, R.id.tv_pass3);
        mPwdTvList[3] = UIUtil.findViewById(view, R.id.tv_pass4);
        mPwdTvList[4] = UIUtil.findViewById(view, R.id.tv_pass5);
        mPwdTvList[5] = UIUtil.findViewById(view, R.id.tv_pass6);
        mPasswordView = UIUtil.findViewById(view, R.id.password_view);
        mPasswordView.setTvList(mPwdTvList);
        mPasswordView.setOnFinishInput(new PasswordView.OnPasswordInputCallback() {
            @Override
            public void inputFinish() {
                mPassworAlert.dismiss();
                submitWithdrawDeposit(mPasswordView.getStrPassword());
            }

            private void submitWithdrawDeposit(String pwd) {
                //余额支付 提交密码
                amountPay(pwd);
            }
        });
        mPassworAlert.addExtView(view);
        mPassworAlert.setOnDismissListener(new OnAlertDismissListener() {
            @Override
            public void onDismiss(AlertView alertView) {
                mPasswordView.clearPassword();
            }
        });
    }

    private void amountPay(String pwd) {
        RetroSubscrube.getInstance().postSubscrube(AppUrl.AMOUNT_PAY,
                PostParam.amoutPay(mToken, mBidId, mAddress.getAddressId(), pwd),
                new BaseObserver(PayOrderActivity.this, getString(R.string.loading_submit)) {
                    @Override
                    protected void onHandleSuccess(Object data, String msg) {
                        paySuccess();
                    }
                });
    }

    private void initMsgAlert() {
        mMessageAlert = new AlertView(this, null, "尚未设置交易密码，是否设置交易密码", getString(R.string.cancel),
                new String[]{getString(R.string.confirm)}, null, AlertView.Style.Alert, new
                OnAlertItemClickListener() {
                    @Override
                    public void onItemClick(AlertView alertView, int position) {
                        switch (position) {
                            case 0:
                                Bundle extras = new Bundle();
                                extras.putBoolean(IntentKey.MODIFY_FOR_PAYPWD, true);
                                ShowActivity.showActivity(getContext(), BindPhoneActivity.class, extras);
                                break;
                        }
                    }
                });
    }

    private void paySuccess() {
        Bundle extras = new Bundle();
        extras.putInt(IntentKey.FROM, 1);
        extras.putString(IntentKey.TITLE_MESSAGE, getString(R.string.pay_success));
        extras.putString(IntentKey.SUCCESS_MESSAGE, getString(R.string.pay_success_message));
        ShowActivity.showActivityForResult(getContext(), SucceedActivity.class, extras, RequestCodeKey.GO_PAY);
    }

    private void showWidget(boolean mAddressIsEmpty) {
        mAddressAddTv.setVisibility(mAddressIsEmpty ? View.VISIBLE : View.GONE);
        mUsernameTv.setVisibility(mAddressIsEmpty ? View.GONE : View.VISIBLE);
        mMobileTv.setVisibility(mAddressIsEmpty ? View.GONE : View.VISIBLE);
        mIsDefaultTv.setVisibility(mAddressIsEmpty ? View.GONE : View.VISIBLE);
        mAddressTv.setVisibility(mAddressIsEmpty ? View.GONE : View.VISIBLE);
    }

    private void parseAddress() {
        mUsernameTv.setText(mAddress.getName());
        mMobileTv.setText(mAddress.getMobile());
        mAddressTv.setText(mAddress.getDetailAddress());
        mIsDefaultTv.setVisibility(mAddress.isDefault() ? View.VISIBLE : View.INVISIBLE);
    }

//    private void getBank() {
//        RetroSubscrube.getInstance().getSubscrube(GetParam.getBank(mToken),
//                new BaseObserver(this, getString(R.string.loading_data)) {
//                    @Override
//                    protected void onHandleSuccess(Object data, String msg) {
//                        if (data != null) {
//                            setdefaultBank();
//                            BankCard bankCard = GsonUtil.parseData(data, BankCard.class);
//                            if (!CommonUtil.isEmpty(bankCard.getBankList())) {
//                                dataList.addAll(bankCard.getBankList());
//                            }
//                            BankCard.Data addBank = new BankCard.Data();
//                            addBank.setBank("添加银行卡");
//                            dataList.add(addBank);
//                            mAdapter.refreshData(dataList);
//                        }
//                    }
//                });
//    }

//    @Override
//    public void onItemClick(RecyclerHolder holder, View view, int position) {
//        BankCard.Data data = dataList.get(position);
//        for (BankCard.Data d : dataList) {
//            d.setIsSelect(0);
//        }
//        dataList.get(position).setIsSelect(1);
//        mAdapter.refreshData(dataList);
//        switch (data.getBank()) {
//            case "钱包余额":
//                mPayStatus = 3;
//                break;
//            case "添加银行卡":
//                ShowActivity.showActivityForResult(this, BankCardAddActivity.class, RequestCodeKey.GO_ADD_BANKCARD);
//                break;
//            default:
//                bankNumber = data.getBankcardNo();
//                mPayStatus = 1;
//                break;
//        }
//
//    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    private class MyOnCheckedChangedListener implements RadioGroup.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(RadioGroup radioGroup, @IdRes int checkedId) {
            switch (checkedId) {
                case R.id.payorder_paystyle_online_rb:
                    mPayStatus = 3;
                    rv_walter_pay.setVisibility(View.VISIBLE);
                    imvCheckPay.setSelected(true);
                    break;
                case R.id.payorder_paystyle_offline_rb:
                    mPayStatus = 2;
                    rv_walter_pay.setVisibility(View.GONE);
                    break;
            }
        }
    }

}
